package ck.mmd.action;

import java.io.ByteArrayInputStream;  
import java.io.IOException;
import java.util.Map;  

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
  



import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;  
  



import ck.mmd.util.SecurityCode;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;  

  
  
public class SecurityCodeImageAction  extends ActionSupport  implements SessionAware{  
    private static final long serialVersionUID = 1496691731440581303L;  
 
	//图片流  
    private ByteArrayInputStream imageStream;  
    //session域  
    private Map<String, Object> session; 
      
    public ByteArrayInputStream getImageStream() {  
        return imageStream;  
    }  
    public void setImageStream(ByteArrayInputStream imageStream) {  
        this.imageStream = imageStream;  
    }  
    public void setSession(Map<String, Object> session) {  
        this.session = session;  
    }  
    
	public String tologin(){
    	HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("url");
		if(id == null || id.equals("")){
			return "tologin";
		}
		if(id != null || id.equals("") == false){
			ActionContext.getContext().getSession().put("sessionurl", id);
		}
    	return "tologin";
    }
    
    public String toregist(){
    	return "toregist";
    }
    
    public String execute() throws Exception {   
        //获取默认难度和长度的验证码  
        String securityCode = SecurityCode.getSecurityCode();  
        imageStream = ck.mmd.util.SecurityImage.getImageAsInputStream(securityCode);  
        //放入session中  
        session.put("securityCode", securityCode);
        return SUCCESS;  
    }
    
    /**
     * 校验验证码是否正确
     * @return 返回登录视图
     */
	public String ajaxValidateCode() throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		
		//获取输入的校验码
		String code = request.getParameter("valicode");
		
		//获取真正的校验码
		String vali = (String) request.getSession().getAttribute("securityCode");
				
		boolean b = code.equals(vali);
		//发送给客户端
		
		response.getWriter().print(b);
		return null;
	} 
	
	public String ajaxValidateCode2() throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		
		//获取输入的校验码
		String code = request.getParameter("yanzheng");
		
		//获取真正的校验码
		String vali = (String) request.getSession().getAttribute("securityCode");
		
		boolean b = code.equals(vali);
		//发送给客户端
		
		response.getWriter().print(b);
		return null;
	} 
}
